package top.littlejiang.onlinexam.controller;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import top.littlejiang.onlinexam.common.base.BusinessException;
import top.littlejiang.onlinexam.common.utils.JSONUtils;
import top.littlejiang.onlinexam.common.utils.JWTUtils;
import top.littlejiang.onlinexam.common.utils.Result;
import top.littlejiang.onlinexam.service.OlexamMenuRoleService;
import top.littlejiang.onlinexam.service.OlexamMenuService;
import top.littlejiang.onlinexam.vo.MenuVO;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chen
 * @Description
 * @since 2021/2/26 20:02
 */
@Controller
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    OlexamMenuService menuService;
    @Autowired
    OlexamMenuRoleService menuRoleService;

    /**
     * 登录用户 可点击菜单
     * @return
     */
    @ResponseBody
    @PostMapping("/get")
    @RequiresPermissions("olexam:home:home")
    public Result get(){
        if (JWTUtils.getUserId() == 0){
            throw new BusinessException("系统错误！获取菜单失败！");
        }

        List<MenuVO> menuList = menuService.getMenuList(JWTUtils.getUserId());
        return Result.ok(JSONUtils.beanToJson(menuList));
    }

    /**
     * 对应角色修改菜单列表
     * @param roleId
     * @return
     */
    @GetMapping("/menurole/{roleId}")
    @ResponseBody
    public Result menuRole(@PathVariable("roleId") Integer roleId){
        if (roleId < 0){
            throw new BusinessException("查询角色失败！");
        }
        List<MenuVO> menus = menuService.getList();
        List<Integer> checked = menuRoleService.getMenusByRole(roleId);
        Map<String,Object> res = new HashMap<>(2);
        res.put("menutree", menus);
        res.put("checked", checked);
        return Result.ok(res);
    }
}
